package apigateway.project.core.request;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import lombok.Data;
import lombok.Getter;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;

import java.nio.charset.Charset;

@Data
public class GlobalRequest {
    /**
     *
     */
    private FullHttpRequest httpRequest;
    /**
     * 请求路径
     */
    private String path;
    /**
     * 请求时间
     */
    private final long beginTime;
    /**
     * 字符集
     */
    private final Charset charset;
    /**
     *  客户端IP
     */
     private final String clientIp;

     /**
     * 请求的地址：IP：port
     */
    private final String host;
    /**
     * 实际请求的 Ip:port (由lbFilter确定)
     */
    private String modifyHost;
    /**
     * 通过网关请求服务的uri : http://gateway//xxx/xx?xx
     */
    private final String uri;

    /**
     * 请求方法
     */
    private final HttpMethod method;


    /**
     * 请求的格式
     */
    private final String contentType;

    /**
     * 请求头信息
     */
    private final HttpHeaders headers;

    /**
     * 参数解析器
     */
    @Getter
    private final QueryStringDecoder queryStringDecoder;

    /**
     * 请求体
     */
    @Getter
    private String body;
    /**
     * 构建下游请求的http请求构建器
     */
    private final RequestBuilder requestBuilder;

    public GlobalRequest(String host, String uri, HttpMethod method, String clientIp, Charset charset, String contentType, HttpHeaders headers, FullHttpRequest httpRequest) {
        this.host = host;
        this.uri = uri;
        this.method = method;
        this.clientIp = clientIp;
        this.charset = charset;
        this.httpRequest = httpRequest;
        this.headers = headers;
        this.beginTime = System.currentTimeMillis();
        this.queryStringDecoder = new QueryStringDecoder(uri,charset);
        this.path = queryStringDecoder.path();
        this.contentType = contentType;

        this.requestBuilder = new RequestBuilder();
        this.requestBuilder.setMethod(getMethod().name());
        this.requestBuilder.setHeaders(getHeaders());
        //设置uri后面的参数
        this.requestBuilder.setQueryParams(queryStringDecoder.parameters());

        ByteBuf content = httpRequest.content();
        if(content!=null) {
            this.requestBuilder.setBody(content.nioBuffer());
        }
    }

    /**
     * 返回下游服务的URL
     * @param isSafeHttp
     * @return
     */
    private String getUrl(boolean isSafeHttp){
        String url = "";
        if(!isSafeHttp ) {
            url ="http://"+modifyHost+"/"+path; }
        else {
            url ="https://"+modifyHost+"/"+path; }
        return url;
    }
    public Request build() {

        requestBuilder.setUrl(getUrl(false));

        //TODO 如果有鉴权过滤器,可以设置header

        return requestBuilder.build();
    }
}
